//
//  HMSQLiteManager.swift
//  大深圳微博01
//
//  Created by shenzhenIOS on 16/4/23.
//  Copyright © 2016年 shenzhenIOS. All rights reserved.
//

import UIKit

import FMDB

// 1.打开数据库
// 2.创建数据表
// 3.操作数据

class HMSQLiteManager: NSObject {

    static let sharedManager: HMSQLiteManager = HMSQLiteManager()
    
    let dbQueue: FMDatabaseQueue
    
    private override init() {
        // 数据库路径
        let dbPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/status.db"
        
        print("dbPath: \(dbPath)")
        dbQueue = FMDatabaseQueue(path: dbPath)
        super.init()
        createTable()
    }
    
    private func createTable() {
        // 读取文件中的sql语句来执行
        let tablesPath = NSBundle.mainBundle().pathForResource("tables", ofType: "sql")!
        // 读取文件
        
        let tables = try! NSString(contentsOfFile: tablesPath, encoding: NSUTF8StringEncoding)
//        print("tables: \(tables)")
        
        // 执行多条sql语句
        dbQueue.inDatabase { (db) -> Void in
            if db.executeStatements(tables as String) {
                print("执行成功")
            } else {
                print("执行失败")
            }
        }
    }
}
